#include "T_Graphics.h"
#include "Def.h"
#include "ElaToolButton.h"
#include "ElaMenu.h"
#include "ElaTableView.h"
#include "T_CaptionTableViewModel.h"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <qglobal.h>
#include <qgraphicsitem.h>

#include "ElaApplication.h"

#include "mainwindow.h"

WardGraphics::WardGraphics(QWidget* parent)
    : T_BasePage(parent)
{
    // 预览窗口标题
    // setWindowTitle("监控");
    // 顶部元素
    // createCustomWidget("图形视图框架被放置于此，可在此界面体验其效果，按住Ctrl进行缩放，按住Shitf进行连接");

    QWidget* centralWidget = new QWidget(this);
    centralWidget->setWindowTitle("主预览");
    setTitleVisible(false);

    // TODO: try restore these, try test without log in
    btn_vid_display = new ElaToggleButton(this);
    btn_vid_save = new ElaToggleButton(this);
    btn_vid_display->setText("视频播放");
    btn_vid_save->setText("录制");
    btn_aud_display = new ElaToggleButton(this);
    btn_aud_display->setText("音频");
    sw_talking_detect = new ElaToggleSwitch(this);
    ElaText* sw_talking_detect_text = new ElaText("人声检测", this);
    sw_talking_detect_text->setTextPixelSize(15);
    // btn_talking_detect->setText("人声检测");

    // ElaTreeView
    T_TreeViewModel* treeModel = new T_TreeViewModel(this);
    QHBoxLayout* treeLayout = new QHBoxLayout();
    treeLayout->setContentsMargins(0, 0, 10, 0);

    // // TreeView
    // _treeView = new ElaTreeView(this);
    // ElaScrollBar* treeViewFloatScrollBar = new ElaScrollBar(_treeView->verticalScrollBar(), _treeView);
    // treeViewFloatScrollBar->setIsAnimation(true);
    // QFont headerFont = _treeView->header()->font();
    // headerFont.setPixelSize(16);
    // _treeView->header()->setFont(headerFont);
    // _treeView->setFixedWidth(130);
    // _treeView->setModel(treeModel);
    // treeLayout->addWidget(_treeView);

    // GraphicsView
    scene = new QGraphicsScene(this);

    view = new QGraphicsView(scene);
    view->setScene(scene);

    addCamera("cam0");
    addCamera("cam1");
    addCamera("cam2");
    addCamera("cam3");

    // 右侧分析列表
    ElaTableView* _captionTableView = new ElaTableView(this);

    // 字体设置
    QFont caption_tableHeaderFont = _captionTableView->horizontalHeader()->font();
    caption_tableHeaderFont.setPixelSize(16);
    _captionTableView->horizontalHeader()->setFont(caption_tableHeaderFont);

    // 模型设置
    caption_list = new T_CaptionTableViewModel(this);
    _captionTableView->setModel(caption_list);

    // 自适应核心配置
    _captionTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); // 时间列
    _captionTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);         // 内容列
    _captionTableView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);              // 尺寸策略

    // 优化显示配置
    _captionTableView->setAlternatingRowColors(true);
    _captionTableView->setIconSize(QSize(38, 38));
    _captionTableView->verticalHeader()->setHidden(true);
    _captionTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    _captionTableView->horizontalHeader()->setMinimumSectionSize(100);  // 时间列最小宽度
    _captionTableView->verticalHeader()->setMinimumSectionSize(36);   // 最小行高
    _captionTableView->verticalHeader()->setDefaultSectionSize(36);    // 默认行高

    QHBoxLayout* viewLayout = new QHBoxLayout();
    viewLayout->setContentsMargins(0, 0, 12, 0);
    viewLayout->addLayout(treeLayout, 1);
    viewLayout->addWidget(view, 6);
    viewLayout->addWidget(_captionTableView, 3);

    QHBoxLayout* topbarLayout = new QHBoxLayout();
    topbarLayout->setContentsMargins(0, 0, 12, 0);
    topbarLayout->addWidget(btn_vid_display);
    topbarLayout->addWidget(btn_vid_save);
    topbarLayout->addWidget(btn_aud_display);
    topbarLayout->addStretch();
    topbarLayout->addWidget(sw_talking_detect_text);
    topbarLayout->addWidget(sw_talking_detect);

    QVBoxLayout* centerVLayout = new QVBoxLayout(centralWidget);
    centerVLayout->setContentsMargins(0, 0, 0, 0);
    centerVLayout->addLayout(topbarLayout);
    centerVLayout->addLayout(viewLayout);
    addCentralWidget(centralWidget, true, false, 0);

    // view->fitInView(scene->sceneRect(), Qt::KeepAspectRatio);

    connect(btn_vid_display,      &ElaToggleButton::toggled, qobject_cast<MainWindow*>(parent), &MainWindow::toggle_video_display);
    connect(btn_vid_save,  &ElaToggleButton::toggled, qobject_cast<MainWindow*>(parent), &MainWindow::toggle_video_saving);
    connect(btn_aud_display,  &ElaToggleButton::toggled, qobject_cast<MainWindow*>(parent), &MainWindow::toggle_audio_display);
    connect(sw_talking_detect,  &ElaToggleSwitch::toggled, qobject_cast<MainWindow*>(parent), &MainWindow::toggle_talking_detect);

    // 连接视图尺寸变化信号（确保使用QGraphicsView的resize事件）
    // connect(view, &QGraphicsView::viewportResized, this, &WardGraphics::handleViewResize);
    // connect(view->viewport(), &QWidget::resized, this, &WardGraphics::handleViewResize);
    // connect(video0, &CustomGraphicsPixmapItem::hovered, this, [&]() {
    //     std::cout << "video0 hovered" << std::endl;
    // });
    // connect(video0, &CustomGraphicsPixmapItem::clicked, this, [&]() {
    //     std::cout << "video0 clicked" << std::endl;
    // });

    //     // 连接交换信号
    // connect(video0, &CustomGraphicsPixmapItem::requestSwapPosition, 
    //         this, &WardGraphics::swapCameraPosition);
    // connect(video1, &CustomGraphicsPixmapItem::requestSwapPosition, 
    //         this, &WardGraphics::swapCameraPosition);
    // connect(video2, &CustomGraphicsPixmapItem::requestSwapPosition, 
    //         this, &WardGraphics::swapCameraPosition);
    // connect(video3, &CustomGraphicsPixmapItem::requestSwapPosition, 
    //         this, &WardGraphics::swapCameraPosition);

}

WardGraphics::~WardGraphics()
{
}

// 设置布局行列数
void WardGraphics::setGridLayout(int rows, int cols) {
    if (rows <=0 || cols <=0) return;
    grid_rows = rows;
    grid_cols = cols;
    updateAllItemsPosition();
}

// 添加摄像头
void WardGraphics::addCamera(const QString &cameraId) {
    if (cameraMap.contains(cameraId)) return;

    CustomGraphicsPixmapItem *item = new CustomGraphicsPixmapItem(cameraId);
    scene->addItem(item);
    videoItems.append(item);
    cameraMap[cameraId] = item;

    // 分配初始网格坐标（按添加顺序）
    int index = videoItems.size() - 1;
    int row = index / grid_cols;
    int col = index % grid_cols;
    gridPositions[cameraId] = QPoint(col, row);  // QPoint(x=列, y=行)

    // 连接信号
    connect(item, &CustomGraphicsPixmapItem::requestSwapPosition, 
            this, &WardGraphics::swapCameraPosition);
    connect(item, &CustomGraphicsPixmapItem::clicked, 
            this, [this, cameraId]() { qDebug() << "摄像头被点击:" << cameraId; });
    connect(item, &CustomGraphicsPixmapItem::hovered, 
            this, [this, cameraId](bool entered) { 
                qDebug() << "摄像头" << cameraId << (entered ? "悬停进入" : "悬停离开"); 
            });

    updateAllItemsPosition();
}

void WardGraphics::resizeEvent(QResizeEvent* event)
{
    // 调用基类的 resizeEvent 方法
    T_BasePage::resizeEvent(event);

    // 触发 handleViewResize
    handleViewResize();
}

// 更新所有项的位置
void WardGraphics::updateAllItemsPosition() {
    QSize viewSize = view->size();
    int itemWidth = viewSize.width() / grid_cols;
    int itemHeight = viewSize.height() / grid_rows;

    for (auto *item : videoItems) {
        QString cameraId = item->getCameraId();
        QPoint grid = gridPositions.value(cameraId, QPoint(-1, -1));
        if (grid.x() == -1) continue; // 无效坐标跳过
        qDebug() << "摄像头" << cameraId << "网格坐标:" << grid;

        int x = grid.x() * itemWidth;
        int y = grid.y() * itemHeight;
        item->setPos(x, y);
    }
}

// 视图大小变化处理
void WardGraphics::handleViewResize() {
    updateAllItemsPosition();
}

// 实际交换位置的槽函数
void WardGraphics::swapCameraPosition(const QString &sourceId, QPoint targetGrid) {
    // 获取源摄像头项
    CustomGraphicsPixmapItem *sourceItem = cameraMap.value(sourceId);
    if (!sourceItem) return;

    // 查找当前占据目标网格的摄像头ID
    QString targetId;
    for (auto it = gridPositions.begin(); it != gridPositions.end(); ++it) {
        if (it.value() == targetGrid) {
            targetId = it.key();
            break;
        }
    }
    if (targetId.isEmpty()) return; // 目标网格无摄像头

    // 交换两者的网格坐标
    QPoint sourceGrid = gridPositions[sourceId];
    gridPositions[sourceId] = targetGrid;
    gridPositions[targetId] = sourceGrid;

    // 更新布局记录
    updateAllItemsPosition();
}

int WardGraphics::pic_update(QImage img, int id) {
    if (id < 0 || id >= videoItems.size()) return -1;

    QPixmap p = QPixmap::fromImage(img);
    QSize viewSize = view->size();

    // 动态计算尺寸
    int itemWidth = viewSize.width() / grid_cols;
    int itemHeight = viewSize.height() / grid_rows;
    // p = p.scaled(itemWidth, itemHeight, Qt::KeepAspectRatio);
    p = p.scaledToWidth(itemWidth);

    videoItems[id]->setPixmap(p);
    view->update();
    return 0;
}

void CustomGraphicsPixmapItem::showContextMenu(const QPoint &screenPos) {
    WardGraphics *parentView = qobject_cast<WardGraphics*>(scene()->parent());
    if (!parentView) return;

    QMenu menu;
    // 获取当前网格坐标
    QPointF currentScenePos = scenePos();
    QSize viewSize = parentView->view->size();
    int gridWidth = viewSize.width() / parentView->grid_cols;
    int gridHeight = viewSize.height() / parentView->grid_rows;
    
    QPoint currentGrid(
        static_cast<int>(currentScenePos.x() / gridWidth),
        static_cast<int>(currentScenePos.y() / gridHeight)
    );

    // 生成所有网格位置
    QList<QPoint> allGrids;
    for (int y = 0; y < parentView->grid_rows; ++y) {
        for (int x = 0; x < parentView->grid_cols; ++x) {
            allGrids.append(QPoint(x, y));
        }
    }

    // 添加菜单项
    foreach (const QPoint &grid, allGrids) {
        if (grid == currentGrid) continue;
        QAction *action = menu.addAction(QString("移动到 (%1, %2)").arg(grid.x()).arg(grid.y()));
        connect(action, &QAction::triggered, [this, grid]() {
            emit requestSwapPosition(cameraId, grid);
        });
    }

    menu.exec(screenPos);
}
